<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,Note," />





  <link rel="alternate" href="/atom.xml" title="GrantonZhuang's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="这篇文章是读书笔记，主要内容为 BroadcastReceiver 的工作过程。">
<meta property="og:type" content="article">
<meta property="og:title" content="BroadcastReceiver 的工作过程">
<meta property="og:url" content="https://grantonzhuang.github.io/2016/09/02/BroadcastReceiverWorkProcess/index.html">
<meta property="og:site_name" content="GrantonZhuang's Blog">
<meta property="og:description" content="这篇文章是读书笔记，主要内容为 BroadcastReceiver 的工作过程。">
<meta property="og:updated_time" content="2016-09-02T15:50:04.177Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="BroadcastReceiver 的工作过程">
<meta name="twitter:description" content="这篇文章是读书笔记，主要内容为 BroadcastReceiver 的工作过程。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://grantonzhuang.github.io/2016/09/02/BroadcastReceiverWorkProcess/"/>

  <title> BroadcastReceiver 的工作过程 | GrantonZhuang's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">GrantonZhuang's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                BroadcastReceiver 的工作过程
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-09-02T23:47:25+08:00" content="2016-09-02">
              2016-09-02
            </time>
          </span>

          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这篇文章是读书笔记，主要内容为 BroadcastReceiver 的工作过程。</p>
<a id="more"></a>
<h2 id="注册的过程"><a href="#注册的过程" class="headerlink" title="注册的过程"></a>注册的过程</h2><h3 id="入口"><a href="#入口" class="headerlink" title="入口"></a>入口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"> <span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> Intent <span class="title">registerReceiver</span><span class="params">(</span></span></div><div class="line">    BroadcastReceiver receiver, IntentFilter filter) &#123;</div><div class="line">    <span class="keyword">return</span> mBase.registerReceiver(receiver, filter);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>与 Activity 和 Service 一样，通过内置的 ContextImpl 完成注册广播的工作。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> Intent <span class="title">registerReceiver</span><span class="params">(BroadcastReceiver receiver, IntentFilter filter,</span></span></div><div class="line">        String broadcastPermission, Handler scheduler) &#123;</div><div class="line">    <span class="keyword">return</span> registerReceiverInternal(receiver, getUserId(),</div><div class="line">            filter, broadcastPermission, scheduler, getOuterContext());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="BroadcastReceiver-和-InnerReceiver"><a href="#BroadcastReceiver-和-InnerReceiver" class="headerlink" title="BroadcastReceiver 和 InnerReceiver"></a><code>BroadcastReceiver</code> 和 <code>InnerReceiver</code></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> Intent <span class="title">registerReceiverInternal</span><span class="params">(BroadcastReceiver receiver, <span class="keyword">int</span> userId,</span></span></div><div class="line">        IntentFilter filter, String broadcastPermission,</div><div class="line">        Handler scheduler, Context context) &#123;</div><div class="line">    IIntentReceiver rd = <span class="keyword">null</span>;</div><div class="line">    <span class="keyword">if</span> (receiver != <span class="keyword">null</span>) &#123;</div><div class="line">        <span class="keyword">if</span> (mPackageInfo != <span class="keyword">null</span> &amp;&amp; context != <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">if</span> (scheduler == <span class="keyword">null</span>) &#123;</div><div class="line">                scheduler = mMainThread.getHandler();</div><div class="line">            &#125;</div><div class="line">            rd = mPackageInfo.getReceiverDispatcher(</div><div class="line">                receiver, context, scheduler,</div><div class="line">                mMainThread.getInstrumentation(), <span class="keyword">true</span>);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">if</span> (scheduler == <span class="keyword">null</span>) &#123;</div><div class="line">                scheduler = mMainThread.getHandler();</div><div class="line">            &#125;</div><div class="line">            rd = <span class="keyword">new</span> LoadedApk.ReceiverDispatcher(</div><div class="line">                    receiver, context, scheduler, <span class="keyword">null</span>, <span class="keyword">true</span>).getIIntentReceiver();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">return</span> ActivityManagerNative.getDefault().registerReceiver(</div><div class="line">                mMainThread.getApplicationThread(), mBasePackageName,</div><div class="line">                rd, filter, broadcastPermission, userId);</div><div class="line">    &#125; <span class="keyword">catch</span> (RemoteException e) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这个方法的思路类似于 Service 的绑定过程中 <code>bindServiceCommon()</code> 方法，由于 BroadcastReceiver 并不能用于进程间通信，所以需要 <code>IIntentReceiver</code> 对象，作为 <code>IBinder</code> 对象，<code>IIntentReceiver</code> 的实现是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">LoadedApk.ReceiverDispatcher.InnerReceiver</div></pre></td></tr></table></figure>
<p>而 <code>ReceiverDispatcher</code> 中同时保存了 <code>BroadcastReceiver</code> 和 <code>InnerReceiver</code>.</p>
<p>这样，在进程间通信的时候，会根据 <code>InnerReceiver</code> 找到 <code>BroadcastReceiver</code> 从而调用 <code>BroadcastReceiver</code> 的 <code>onReceive()</code> 方法。这一个思路与 Service 完全一致。</p>
<h3 id="AMS-中的处理"><a href="#AMS-中的处理" class="headerlink" title="AMS 中的处理"></a>AMS 中的处理</h3><p>上面代码中的最后部分，一样交给了 AMS 处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">return</span> ActivityManagerNative.getDefault().registerReceiver(</div><div class="line">    mMainThread.getApplicationThread(), mBasePackageName,</div><div class="line">    rd, filter, broadcastPermission, userId);</div></pre></td></tr></table></figure>
<p>AMS 中的主要代码，注册了 Receiver 和 Filter</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">mRegisteredReceivers.put(receiver.asBinder(), rl);</div><div class="line"></div><div class="line">BroadcastFilter bf = <span class="keyword">new</span> BroadcastFilter(filter, rl, callerPackage,</div><div class="line">        permission, callingUid, userId);</div><div class="line">rl.add(bf);</div><div class="line"><span class="keyword">if</span> (!bf.debugCheck()) &#123;</div><div class="line">    Slog.w(TAG, <span class="string">"==&gt; For Dynamic broadcast"</span>);</div><div class="line">&#125;</div><div class="line">mReceiverResolver.addFilter(bf);</div></pre></td></tr></table></figure>
<h2 id="发送和接收的过程"><a href="#发送和接收的过程" class="headerlink" title="发送和接收的过程"></a>发送和接收的过程</h2><h3 id="入口-1"><a href="#入口-1" class="headerlink" title="入口"></a>入口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendBroadcast</span><span class="params">(Intent intent)</span> </span>&#123;</div><div class="line">    mBase.sendBroadcast(intent);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在 ContextImpl 中的实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendBroadcast</span><span class="params">(Intent intent)</span> </span>&#123;</div><div class="line">    warnIfCallingFromSystemProcess();</div><div class="line">    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        intent.prepareToLeaveProcess();</div><div class="line">        ActivityManagerNative.getDefault().broadcastIntent(</div><div class="line">                mMainThread.getApplicationThread(), intent, resolvedType, <span class="keyword">null</span>,</div><div class="line">                Activity.RESULT_OK, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, AppOpsManager.OP_NONE, <span class="keyword">null</span>, <span class="keyword">false</span>, <span class="keyword">false</span>,</div><div class="line">                getUserId());</div><div class="line">    &#125; <span class="keyword">catch</span> (RemoteException e) &#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Failure from system"</span>, e);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>AMS 中的实现</p>
<ul>
<li><code>broadcastIntent</code></li>
<li><code>broadcastIntentLocked</code></li>
</ul>
<h3 id="broadcastIntentLocked-方法细节"><a href="#broadcastIntentLocked-方法细节" class="headerlink" title="broadcastIntentLocked 方法细节"></a>broadcastIntentLocked 方法细节</h3><p><code>intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);</code></p>
<p>方法的开头有这样一行，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * If set, this intent will not match any components in packages that</div><div class="line"> * are currently stopped.  If this is not set, then the default behavior</div><div class="line"> * is to include such applications in the result.</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> FLAG_EXCLUDE_STOPPED_PACKAGES = <span class="number">0x00000010</span>;</div></pre></td></tr></table></figure>
<p>表示广播不会发送给已经关闭的应用，如果需要做广播唤醒的功能，可以给 intent 设置另一个 flag</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * If set, this intent will always match any components in packages that</div><div class="line"> * are currently stopped.  This is the default behavior when</div><div class="line"> * &#123;<span class="doctag">@link</span> #FLAG_EXCLUDE_STOPPED_PACKAGES&#125; is not set.  If both of these</div><div class="line"> * flags are set, this one wins (it allows overriding of exclude for</div><div class="line"> * places where the framework may automatically set the exclude flag).</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> FLAG_INCLUDE_STOPPED_PACKAGES = <span class="number">0x00000020</span>;</div></pre></td></tr></table></figure>
<p>在方法的末端，AMS 将广播交给了 <code>BroadcastQueue</code> 处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> ((receivers != <span class="keyword">null</span> &amp;&amp; receivers.size() &gt; <span class="number">0</span>)</div><div class="line">        || resultTo != <span class="keyword">null</span>) &#123;</div><div class="line">    BroadcastQueue queue = broadcastQueueForIntent(intent);</div><div class="line">    BroadcastRecord r = <span class="keyword">new</span> BroadcastRecord(queue, intent, callerApp,</div><div class="line">            callerPackage, callingPid, callingUid, resolvedType,</div><div class="line">            requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,</div><div class="line">            resultData, resultExtras, ordered, sticky, <span class="keyword">false</span>, userId);</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, <span class="string">"Enqueueing ordered broadcast "</span> + r</div><div class="line">            + <span class="string">": prev had "</span> + queue.mOrderedBroadcasts.size());</div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,</div><div class="line">            <span class="string">"Enqueueing broadcast "</span> + r.intent.getAction());</div><div class="line"></div><div class="line">    <span class="keyword">boolean</span> replaced = replacePending &amp;&amp; queue.replaceOrderedBroadcastLocked(r);</div><div class="line">    <span class="keyword">if</span> (!replaced) &#123;</div><div class="line">        queue.enqueueOrderedBroadcastLocked(r);</div><div class="line">        queue.scheduleBroadcastsLocked();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="BroadcastQueue-中的处理"><a href="#BroadcastQueue-中的处理" class="headerlink" title="BroadcastQueue 中的处理"></a>BroadcastQueue 中的处理</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scheduleBroadcastsLocked</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, <span class="string">"Schedule broadcasts ["</span></div><div class="line">            + mQueueName + <span class="string">"]: current="</span></div><div class="line">            + mBroadcastsScheduled);</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (mBroadcastsScheduled) &#123;</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, <span class="keyword">this</span>));</div><div class="line">    mBroadcastsScheduled = <span class="keyword">true</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里使用了 Handler 对象发送消息的形式，来看 <code>BroadcastHandler#handleMessage()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">case</span> BROADCAST_INTENT_MSG: &#123;</div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST) Slog.v(</div><div class="line">            TAG_BROADCAST, <span class="string">"Received BROADCAST_INTENT_MSG"</span>);</div><div class="line">    processNextBroadcast(<span class="keyword">true</span>);</div><div class="line">&#125; <span class="keyword">break</span>;</div></pre></td></tr></table></figure>
<p>processNextBroadcast 中的处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//...</span></div><div class="line"><span class="comment">// First, deliver any non-serialized broadcasts right away.</span></div><div class="line"><span class="keyword">while</span> (mParallelBroadcasts.size() &gt; <span class="number">0</span>) &#123;</div><div class="line">    r = mParallelBroadcasts.remove(<span class="number">0</span>);</div><div class="line">    r.dispatchTime = SystemClock.uptimeMillis();</div><div class="line">    r.dispatchClockTime = System.currentTimeMillis();</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> N = r.receivers.size();</div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, <span class="string">"Processing parallel broadcast ["</span></div><div class="line">            + mQueueName + <span class="string">"] "</span> + r);</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;N; i++) &#123;</div><div class="line">        Object target = r.receivers.get(i);</div><div class="line">        <span class="keyword">if</span> (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,</div><div class="line">                <span class="string">"Delivering non-ordered on ["</span> + mQueueName + <span class="string">"] to registered "</span></div><div class="line">                + target + <span class="string">": "</span> + r);</div><div class="line">        deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, <span class="keyword">false</span>);</div><div class="line">    &#125;</div><div class="line">    addBroadcastToHistoryLocked(r);</div><div class="line">    <span class="keyword">if</span> (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, <span class="string">"Done with parallel broadcast ["</span></div><div class="line">            + mQueueName + <span class="string">"] "</span> + r);</div><div class="line">&#125;</div><div class="line"><span class="comment">//...</span></div></pre></td></tr></table></figure>
<p>deliverToRegisteredReceiverLocked 的处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//...</span></div><div class="line">performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,</div><div class="line">            <span class="keyword">new</span> Intent(r.intent), r.resultCode, r.resultData,</div><div class="line">            r.resultExtras, r.ordered, r.initialSticky, r.userId);</div><div class="line"><span class="comment">//...</span></div></pre></td></tr></table></figure>
<p>performReceiveLocked 的处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">performReceiveLocked</span><span class="params">(ProcessRecord app, IIntentReceiver receiver,</span></span></div><div class="line">        Intent intent, <span class="keyword">int</span> resultCode, String data, Bundle extras,</div><div class="line">        <span class="keyword">boolean</span> ordered, <span class="keyword">boolean</span> sticky, <span class="keyword">int</span> sendingUser) <span class="keyword">throws</span> RemoteException &#123;</div><div class="line">    <span class="comment">// Send the intent to the receiver asynchronously using one-way binder calls.</span></div><div class="line">    <span class="keyword">if</span> (app != <span class="keyword">null</span>) &#123;</div><div class="line">        <span class="keyword">if</span> (app.thread != <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="comment">// If we have an app thread, do the call through that so it is</span></div><div class="line">            <span class="comment">// correctly ordered with other one-way calls.</span></div><div class="line">            app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,</div><div class="line">                    data, extras, ordered, sticky, sendingUser, app.repProcState);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="comment">// Application has died. Receiver doesn't exist.</span></div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RemoteException(<span class="string">"app.thread must not be null"</span>);</div><div class="line">        &#125;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        receiver.performReceive(intent, resultCode, data, extras, ordered,</div><div class="line">                sticky, sendingUser);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="ApplicationThread-中的处理"><a href="#ApplicationThread-中的处理" class="headerlink" title="ApplicationThread 中的处理"></a>ApplicationThread 中的处理</h3><p>这里的 app.thread 是 <code>IApplicationThread</code> 的实现 <code>ApplicationThread</code></p>
<p><code>ApplicationThread#scheduleRegisteredReceiver</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scheduleRegisteredReceiver</span><span class="params">(IIntentReceiver receiver, Intent intent,</span></span></div><div class="line">        <span class="keyword">int</span> resultCode, String dataStr, Bundle extras, <span class="keyword">boolean</span> ordered,</div><div class="line">        <span class="keyword">boolean</span> sticky, <span class="keyword">int</span> sendingUser, <span class="keyword">int</span> processState) <span class="keyword">throws</span> RemoteException &#123;</div><div class="line">    updateProcessState(processState, <span class="keyword">false</span>);</div><div class="line">    receiver.performReceive(intent, resultCode, dataStr, extras, ordered,</div><div class="line">            sticky, sendingUser);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="ReceiverDispatcher-的处理"><a href="#ReceiverDispatcher-的处理" class="headerlink" title="ReceiverDispatcher 的处理"></a>ReceiverDispatcher 的处理</h3><p>这里的 IIntentReceiver#performReceive 的实现自然是 <code>InnerReceiver#performReceive</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">performReceive</span><span class="params">(Intent intent, <span class="keyword">int</span> resultCode, String data,</span></span></div><div class="line">        Bundle extras, <span class="keyword">boolean</span> ordered, <span class="keyword">boolean</span> sticky, <span class="keyword">int</span> sendingUser) &#123;</div><div class="line">    LoadedApk.ReceiverDispatcher rd = mDispatcher.get();</div><div class="line">    <span class="comment">// ...</span></div><div class="line">    <span class="keyword">if</span> (rd != <span class="keyword">null</span>) &#123;</div><div class="line">        rd.performReceive(intent, resultCode, data, extras,</div><div class="line">                ordered, sticky, sendingUser);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>ReceiverDispatcher#performReceive</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">performReceive</span><span class="params">(Intent intent, <span class="keyword">int</span> resultCode, String data,</span></span></div><div class="line">        Bundle extras, <span class="keyword">boolean</span> ordered, <span class="keyword">boolean</span> sticky, <span class="keyword">int</span> sendingUser) &#123;</div><div class="line">    <span class="keyword">if</span> (ActivityThread.DEBUG_BROADCAST) &#123;</div><div class="line">        <span class="keyword">int</span> seq = intent.getIntExtra(<span class="string">"seq"</span>, -<span class="number">1</span>);</div><div class="line">        Slog.i(ActivityThread.TAG, <span class="string">"Enqueueing broadcast "</span> + intent.getAction() + <span class="string">" seq="</span> + seq</div><div class="line">                + <span class="string">" to "</span> + mReceiver);</div><div class="line">    &#125;</div><div class="line">    Args args = <span class="keyword">new</span> Args(intent, resultCode, data, extras, ordered,</div><div class="line">            sticky, sendingUser);</div><div class="line">    <span class="keyword">if</span> (!mActivityThread.post(args)) &#123;</div><div class="line">        <span class="keyword">if</span> (mRegistered &amp;&amp; ordered) &#123;</div><div class="line">            IActivityManager mgr = ActivityManagerNative.getDefault();</div><div class="line">            <span class="keyword">if</span> (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,</div><div class="line">                    <span class="string">"Finishing sync broadcast to "</span> + mReceiver);</div><div class="line">            args.sendFinished(mgr);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里的 Args 实现了 Runnable 接口</p>
<p><code>final class Args extends BroadcastReceiver.PendingResult implements Runnable</code></p>
<p><code>mActivityThread.post(args)</code> 实际上是使用 handler 发送了一个 ARGS 对象</p>
<p>ARGS 对象的 run 方法实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">    ClassLoader cl =  mReceiver.getClass().getClassLoader();</div><div class="line">    intent.setExtrasClassLoader(cl);</div><div class="line">    setExtrasClassLoader(cl);</div><div class="line">    receiver.setPendingResult(<span class="keyword">this</span>);</div><div class="line">    <span class="comment">// 这里调用了 `receiver.onReceive`</span></div><div class="line">    receiver.onReceive(mContext, intent);</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>由此可以得知，广播接收者的 <code>onReceive</code> 方法也是在主线程中调用的。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/Note/" rel="tag">#Note</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/10/SthAboutServiceLaunch2/" rel="next" title="Service 的启动过程 绑定状态">
                <i class="fa fa-chevron-left"></i> Service 的启动过程 绑定状态
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/09/04/ContentProvider的启动过程/" rel="prev" title="ContentProvider的启动过程">
                ContentProvider的启动过程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww1.sinaimg.cn/mw690/6e8939a6gw1f3g1u1mc6lj20hs0hsmxf.jpg"
               alt="Granton Zhuang" />
          <p class="site-author-name" itemprop="name">Granton Zhuang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives/index.html">
              <span class="site-state-item-count">26</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#注册的过程"><span class="nav-number">1.</span> <span class="nav-text">注册的过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#入口"><span class="nav-number">1.1.</span> <span class="nav-text">入口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BroadcastReceiver-和-InnerReceiver"><span class="nav-number">1.2.</span> <span class="nav-text">BroadcastReceiver 和 InnerReceiver</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AMS-中的处理"><span class="nav-number">1.3.</span> <span class="nav-text">AMS 中的处理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#发送和接收的过程"><span class="nav-number">2.</span> <span class="nav-text">发送和接收的过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#入口-1"><span class="nav-number">2.1.</span> <span class="nav-text">入口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#broadcastIntentLocked-方法细节"><span class="nav-number">2.2.</span> <span class="nav-text">broadcastIntentLocked 方法细节</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BroadcastQueue-中的处理"><span class="nav-number">2.3.</span> <span class="nav-text">BroadcastQueue 中的处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ApplicationThread-中的处理"><span class="nav-number">2.4.</span> <span class="nav-text">ApplicationThread 中的处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ReceiverDispatcher-的处理"><span class="nav-number">2.5.</span> <span class="nav-text">ReceiverDispatcher 的处理</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Granton Zhuang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  

  

  

</body>
</html>
